import React, { useCallback, useEffect } from 'react';
import NavBar from '@/components/NavBar/NavBar';
import { useNavigate } from 'react-router-dom';
import { fetchAddressList } from '@/store/modules/addressStore';
import { Toast } from 'antd-mobile';
import { useEnhanceDispatch, useEnhanceSelector } from '@/hooks';
import AddressItem from '@/views/Address/components/AddressItem/AddressItem';
import SvgIcon from '@/components/SvgIcon/SvgIcon';
import './Address.scss';


const Address = () => {
  const enhanceDispatch = useEnhanceDispatch();
  const addressList = useEnhanceSelector(state => state.addressStore.addressLit);
  const navigate = useNavigate();
  // 左边插槽内容
  const left = useCallback(() => (<span>返回</span>), []);
  // 中间插槽内容
  const children = useCallback(() => (<span>地址列表</span>), []);


  /**
   * @description 获取收获地址的回调函数
   * */
  const fetchAddress = async () => {
    try {
      await enhanceDispatch(fetchAddressList()).unwrap();
    } catch (rejectedValueOrSerializedError: any) {
      Toast.show(rejectedValueOrSerializedError);
    }
  };

  useEffect(() => {
    fetchAddress();
  }, []);

  return (
    <div className="address">
      {/*导航栏组件*/}
      <NavBar back={left()} children={children()} onBack={() => navigate(-1)}></NavBar>
      <div className="address-list">
        {/*地址列表*/}
        {addressList.map((item, index) => <AddressItem address={item} key={item.id}></AddressItem>)}
        {/*=添加地址*/}
        <div className="address-add">
          <SvgIcon name="add" width="20px" height="20px"></SvgIcon>
          <p>添加地址</p>
        </div>
        <div className="address-tip">最多可添加6个地址</div>
      </div>
    </div>
  );
};

export default Address;